<?php

namespace App\Jobs\Finance;

use App\Jobs\Finance\Traits\CommonBranchBillTrait;
use App\Jobs\Finance\Traits\CreateBillTrait;
use App\Jobs\Finance\Traits\FinanceBranchBillTrait;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class StopCustomerBillJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, FinanceBranchBillTrait, CreateBillTrait, CommonBranchBillTrait;

    protected $customer;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($customer)
    {
        //
        $this->customer=$customer;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //终止客户账单时生成客户账单
        $customer=$this->customer;
        if($customer){
            $this->singleCustomerBillCreate($customer);
        }

    }

    //获取账单周期
    public function getBillMonth($customer){
        $day = date('d');
        $lastMonth=date("m", strtotime(-$day.' day'));
        $year=date('Y');
        if($lastMonth==12){
            $year-=1;
        }
        //定时任务生成过账单
        if($this->checkCustomerMonthBill($customer)){
            return date('Y').'年'.date('m').'月';
        }
        //定时任务还没生成账单
        if($customer->advance_order==1){
            return $year.'年'.$lastMonth.'月';
        }
        return $year.'年'.$lastMonth.'-'.date('m').'月';
    }

    //获取账单期
    public function getBillPeriod($customer,$type){
        $today= date("Y/m/d");
        $day = date('d');
        $lastMonth=date("Y/m/", strtotime(-$day.' day'));
        //自然月
        if($customer->advance_order==1){
            if($this->checkCustomerMonthBill($customer)){
                if($type=='start'){
                    return date("Y/m/").'01';
                }
                return $today;
            }
            if($type=='start'){
                return $lastMonth.'01';
            }
            return date("Y/m/d", strtotime(-$day.' day'));
        }
        //非自然月
        $setDay=$customer->settle_date;
        if($this->checkCustomerMonthBill($customer)){
            if($type=='start'){
                if((int)$setDay<10){
                    $setDay='0'.$setDay;
                }
                return date("Y/m/").$setDay;
            }
            return $today;
        }
        if($type=='start'){
            if((int)$setDay<10){
                $setDay='0'.$setDay;
            }
            return $lastMonth.$setDay;
        }
        return $today;
    }


}
